<template>
	<view :style="{overflow:showscoll()?'hidden':'auto'}">
		<view class="headerStyle">
			<view>
				<view @click="changeCurrent(0)" style="width: 33%;height: 75rpx;
				line-height: 75rpx;
				text-align: center;
				padding: 0 10px;
				font-size: 30rpx;float: left" :class="current==0?'menuborder':''">
					待办列表
				</view>
				<view @click="changeCurrent(1)" style="width: 33%;height: 75rpx;
				line-height: 75rpx;
				text-align: center;
				padding: 0 10px;
				font-size: 30rpx;float: left" :class="current==1?'menuborder':''">
					已办列表
				</view>
				<view @click="changeCurrent(2)" style="width: 33%;height: 75rpx;
				line-height: 75rpx;
				text-align: center;
				padding: 0 10px;
				font-size: 30rpx;float: left" :class="current==2?'menuborder':''">
					我发起的	
				</view>
			</view>
		</view>
		<view class="bodystyle">
			<view v-if="current==0">
				<view class="showCard" @click.native="handleRdit(item)" v-for="(item,index) in approveData" :key="index">
					<view style="width: 100%;">
						<view style="width:100%;padding: 8rpx 0;font-size: 30rpx;height: 80rpx;">
							<view style="float: left;">申请人：</view>
							<view style="float: right;">{{item.applierName}}</view>
						</view>
						<view style="width:100%;padding: 8rpx 0;font-size: 30rpx;height: 80rpx;">
							<view style="float: left;">节点名称：</view>
							<view style="float: right;">{{item.nodeName}}</view>
						</view>
						<view style="width:100%;padding: 8rpx 0;font-size: 30rpx;height: 80rpx;">
							<view style="float: left;">审批单号：</view>
							<view style="float: right;">{{item.procInstNo.substr(0,15)}}</view>
						</view>
						<view style="width:100%;padding: 8rpx 0;font-size: 30rpx;height: 80rpx;">
							<view style="float: left;">申请时间：</view>
							<view style="float: right;">{{item.applyTime}}</view>
						</view>
						<!-- <view style="width:100%;padding: 8rpx 0;font-size: 30rpx;height: 60rpx;">
							<view @click="showDetails(item)" class="btnstyle">详情</view>
							<view @click="approveHistory(item)" class="btnstyle">审批历史</view>
							<view @click="handleRdit(item)" class="btnstyle">审批</view>
							<view @click="addSign(item)" class="btnstyle">加签</view>
							<view @click="approveDelegate(item)" class="btnstyle">转办</view>
							<view @click="backApprove(item)" class="btnstyle">退回</view>
						</view> -->
					</view>
				</view>
			</view>
			<view v-if="current==1">
				<view @click="showDoneDetails(item)" class="showCard" v-for="(item,index) in approveData" :key="index">
					<view style="width: 100%;">
						<view style="width:100%;padding: 8upx 0;font-size: 30rpx;height: 80rpx;">
							<view style="float: left;">审批单号：</view>
							<view style="float: right;">{{item.processNo.substr(0,15)}}</view>
						</view>
						<view style="width:100%;padding: 8upx 0;font-size: 30rpx;height: 80rpx;">
							<view style="float: left;">审批状态：</view>
							<view style="float: right;">{{item.approveStatus}}</view>
						</view>
						<view style="width:100%;padding: 8upx 0;font-size: 30rpx;height: 80rpx;">
							<view style="float: left;">耗时：</view>
							<view style="float: right;">{{item.durationStr}}</view>
						</view>
						<view style="width:100%;padding: 8upx 0;font-size: 30rpx;height: 80rpx;">
							<view style="float: left;">审批时间：</view>
							<view style="float: right;">{{item.approveTime}}</view>
						</view>
						<!-- <view style="width:100%;padding: 8upx 0;font-size: 30rpx;">
							<view @click="showDoneDetails(item)" class="btnstyle">详情</view>
							<view @click="approveHistory(item)" class="btnstyle">审批历史</view>
						</view> -->
					</view>
				</view>
			</view>
			<view v-if="current==2">
				<view @click="showDoneDetails(item)" class="showCard" v-for="(item,index) in approveData" :key="index">
					<view style="width: 100%;">
						<view style="width:100%;padding: 8upx 0;font-size: 30rpx;height: 80rpx;">
							<view style="float: left;">申请单号：</view>
							<view style="float: right;">{{item.processNo.substr(0,15)}}</view>
						</view>
						<view style="width:100%;padding: 8upx 0;font-size: 30rpx;height: 80rpx;">
							<view style="float: left;">审批状态：</view>
							<view style="float: right;">{{item.approveStatus}}</view>
						</view>
						<view style="width:100%;padding: 8upx 0;font-size: 30rpx;height: 80rpx;">
							<view style="float: left;">发起审批时间：</view>
							<view style="float: right;">{{item.applyTime}}</view>
						</view>
						<view style="width:100%;padding: 8upx 0;font-size: 30rpx;height: 80rpx;">
							<view style="float: left;">结束时间：</view>
							<view style="float: right;">{{item.finishTime?item.finishTime:'未结束'}}</view>
						</view>
						<!-- <view style="width:100%;padding: 8upx 0;font-size: 30rpx;">
							<view class="btnstyle" @click="approveHistory(item)">审批历史</view>
							<view @click="cancleApprove(item)" class="btnstyle">撤销</view>
						</view> -->
					</view>
				</view>
			</view>
		</view>
		<u-modal width="700rpx" :showCancelButton="true" cancelText="关闭" @cancel="showChange=false" @confirm="submitDelegateForm"
			style="padding: 0!important;" :show="showChange" title="转办">
			<view style="height: 60vh;width: 100%;">
				<view style="width: 100%;height: 85%;overflow-y: scroll;">
					<!-- <u-search v-model="keyword" @change="searchTree" @search="searchTree" :showAction="true"
						actionText="搜索" :animation="true"></u-search> -->
					<u-input placeholder="请输入内容" border="surround" v-model="keyword"></u-input>
					<DaTreeVue2 ref="DaTreeVue2" v-if="treeTimer" :data="roomTreeData" leafField="hasLeaf"
						labelField="label" valueField="primaryCode" :loadMode="true" defaultExpandAll
						@change="handleTreeChange1" @expand="handleExpandChange1" />
				</view>
				<view style="width: 100%;height: 15%;padding: 10rpx;">
					<view class="content" style="font-size: 28rpx;">
						备注：<u-input v-model="delegateData.comment" placeholder="请输入意见"></u-input>
					</view>
				</view>
			</view>
		</u-modal>
		<u-modal width="700rpx" :showCancelButton="true" cancelText="关闭" @cancel="showTree=false" @confirm="submitCountersignForm"
			style="padding: 0!important;" :show="showTree" title="加签">
			<view style="height: 70vh;overflow-y: scroll;">
				<view style="font-size: 28rpx;height: 50px;">
					<view style="float: left;margin-right: 10rpx;">
						加签类型：
					</view>
					<view style="float: left;">
						<radio-group @change="radioChange">
							<view style="transform:scale(0.7);float: left;" v-for="(item, index) in items"
								:key="item.value">
								<radio :value="item.value" :checked="index === currentradio" />
								{{item.name}}
							</view>
						</radio-group>
					</view>
				</view>
				<u-input placeholder="请输入内容" border="surround" v-model="keyword"></u-input>
				<!-- <u-search v-model="keyword" @change="searchTree" @search="searchTree" :showAction="true" actionText="搜索"
					:animation="true"></u-search> -->
				<DaTreeVue2 ref="DaTreeVue2" v-if="treeTimer" :data="roomTreeData" leafField="hasLeaf"
					labelField="label" valueField="primaryCode" showCheckbox :loadMode="true" defaultExpandAll
					@change="handleTreeChange" @expand="handleExpandChange" />
			</view>
		</u-modal>
		<u-modal width="700rpx" :showCancelButton="true" cancelText="关闭" @cancel="backDrawer=false" @confirm="submitBackForm"
			style="padding: 0!important;" :show="backDrawer" title="退回">
			<view style="overflow-y: scroll;width: 100%;">
				<u-form labelPosition="left" :model="backData" ref="uForm">
					<u-form-item labelWidth="120" label="退回到" prop="destNodeId" borderBottom ref="item1">
						<uni-data-select v-model="backData.destNodeId" :localdata="range" @change="change"
							label="应用选择"></uni-data-select>
					</u-form-item>
					<u-form-item labelWidth="120" label="意见" prop="reason">
						<u-input v-model="backData.reason" placeholder="请输入意见"></u-input>
					</u-form-item>
				</u-form>

			</view>
		</u-modal>
		<u-modal width="700rpx" :showCancelButton="true" cancelText="关闭" @cancel="dialogVisible=false" @confirm="cancelProcess"
			style="padding: 0!important;" :show="dialogVisible" title="撤销">
			<view style="width: 100%;">
				<view class="content" style="font-size: 28rpx;">
					<u-input v-model="cancelData.remark" placeholder="请输入备注"></u-input>
				</view>
			</view>
		</u-modal>
		<u-modal @cancel="showDone=false" @confirm="showDone=false" style="padding: 0!important;" width="700rpx" :show="showDone"
			title="详情">
			<view style="width: 100%;height: 80vh;overflow: scroll;">
				<done-detail :formData="formDoneData" :defaultData="defaultDoneData"></done-detail>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import editform from '../approve/comp/editForm.vue'
	import formDetail from './comp/formDetail.vue'
	import global from '@/plugins/global'
	import DaTreeVue2 from '@/components/da-tree-vue2/index.vue'
	import doneDetail from '../approve/doneDetail.vue'
	export default {
		components: {
			editform,
			DaTreeVue2,
			doneDetail
		},
		data() {
			return {
				showDone: false,
				delegateData: {
					'comment': '',
					'delegateUserId': 0,
					'procInstId': 0
				},
				showChange: false,
				keyword: '',
				value: 0,
				range: [],
				showBack: false,
				signForm: {},
				items: [{
						value: '1',
						name: '前加签',
						checked: 'true'
					},
					{
						value: '2',
						name: '后加签'
					}
				],
				currentradio: 0,
				signType: 1,
				addSignForm: {},
				showTree: false,
				handleDrawer: false,
				current: 0,
				approveData: [],
				isEmpty: false,
				isLast: false,
				start: 1,
				defaultData: {},
				formData: {},
				detailDrawer: false,
				formTimer: null,
				handleTimer: null,
				processKey: '',
				applierChooseList: {},
				formAuth: {},
				approveApi: [
					'workbench/todoPage', 'workbench/doneList', 'workbench/myApplyPage'
				],
				historyData: [],
				historyDrawer: false,
				roomTreeData: [],
				CountersignData: {
					procInstId: 0,
					userIds: [],
				},
				backData: {},
				backNodes: [],
				backDrawer: false,
				timer: '',
				selectedDelegateUser: '',
				dialogVisible: false,
				cancelData: {
					'procInstId': 0,
					'remark': ''
				},
				formDoneData: {},
				defaultDoneData: {},
				treeTimer: true
			}
		},
		// 下拉刷新,初始化第一页数据
		onPullDownRefresh() {
			this.initData()
		},
		//页面滚动到底部的事件
		onReachBottom() {
			this.getTodolist();
		},

		onLoad() {
			this.isEmpty = false
			this.isLast = false
			this.start = 1
			this.approveData = []
			uni.setStorageSync('isback',false)
			this.getTodolist();
			this.getTreeData()
			console.log('进来了吗onLoad');
		},
		onShow() {
			let isback = uni.getStorageSync('isback')
			console.log('进来了吗', isback);
			setTimeout(e => {
				if (isback) {
					this.approveData = []
					this.isEmpty = false
					this.isLast = false
					this.start = 1
					this.getTodolist()
					uni.setStorageSync('isback', false)
				}
			}, 200)
		},
		watch: {
			keyword(val) {
				console.log(val, 'huoqu1hiji');
				this.searchTree(val)
			},
		},
		methods: {
			showscoll() {
				return this.showChange || this.showTree || this.backDrawer || this.showDone
			},
			GetApiData() {},
			showDetails(e) {
				console.log(e);
				// this.$request(this.$api['workbench/doneForm'], {
				// 	procInstId: e.procInstId
				// }, data => {
				// 	console.log(data);
				// 	this.defaultDoneData = data;
				// 	this.$request(this.$api['workbench/doneFormDesign'], {
				// 		procInstId: e.procInstId
				// 	}, res => {
				// 		console.log(res);
				// 		this.formDoneData = res.formData;
				// 		this.showDone = true
				// 	})
				// })
			},
			// 审批
			handleRdit(e) {
				this.procInstId = e.procInstId;
				let data = JSON.parse(JSON.stringify(e))
				data.formData = ''
				console.log(e, '数据');
				uni.navigateTo({
					url: "./approve?atype=approve&edata=" + JSON.stringify(data)
				});
				uni.setStorageSync('formData', e.formData)
			},
			//已办详情
			showDoneDetails(e) {
				// e.procInstId = e.id;
				// this.procInstId = e.id;
				// let data = JSON.parse(JSON.stringify(e))
				// data.formData = ''
				// uni.navigateTo({
				// 	url: "./approve?atype=done&edata=" + JSON.stringify(data)
				// });
				// uni.setStorageSync('formData', e.formData)
				let that = this
				e.procInstId = e.id;
				uni.navigateTo({
					url: "./approve?atype=apply&edata=" + JSON.stringify(e)
				});
			},
			cancelProcess() {
				this.$request(this.$api['workbench/processCancel'], this.cancelData, res => {
					uni.$u.toast('该审批已撤销');
					this.dialogVisible = false;
					this.initData()
				})
			},
			cancleApprove(e) {
				console.log(e);
				this.cancelData.procInstId = e.id;
				this.dialogVisible = true;
			},
			// 确定转办
			submitDelegateForm(e) {
				if (!this.delegateData.delegateUserId) {
					console.log(this.delegateData.selectedDelegateUser);
					uni.$u.toast('请选择要转交的用户')
					return false;
				}
				this.$request(this.$api['workbench/delegateapprove'], this.delegateData, res => {
					uni.$u.toast('您已转交给' + this.selectedDelegateUser);
					this.showChange = false;
					this.initData()
				})
			},
			// 搜索树节点
			searchTree(e) {
				console.log(e, e.length, '进来了进来了');
				if (e.length) {
					this.$request(this.$api['workbench/lazyorgusertree'], {
						orgName: e
					}, res => {
						this.roomTreeData = res;
					})
				} else {
					this.getTreeData()
				}
			},
			//转办
			approveDelegate(e) {
				this.showChange = true;
				this.delegateData.procInstId = e.procInstId;
			},
			//初始化数据
			initData() {
				this.isEmpty = false
				this.isLast = false
				this.start = 1
				this.approveData = []
				this.getTodolist()
				setTimeout(function() {
					uni.stopPullDownRefresh();
				}, 1000);
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				});
			},
			change(e) {},
			//点击退回获取退回节点
			backApprove(e) {
				this.backData = {
					destNodeId: '',
					procInstId: 0,
					reason: '',
				};
				let token = uni.getStorageSync('token')
				uni.$u.http.request({
					url: global.BACKEND_URL + "/workflow/process-inst/back-nodes/" + e.procInstId,
					method: 'GET',
					data: {},
					header: {
						Authorization: 'Bearer ' + token,
						TenantId: 0
					}
				}).then(res => {
					console.log(res, 'dopakodkaod');
					if (res.data.code === "S00000") {
						if (res.data.data.length) {
							console.log(res.data, 'dopakodkaod');
							this.range = [];
							this.backData.procInstId = e.procInstId;
							this.backNodes = res.data.data;
							this.backNodes.forEach(row => {
								this.range.push({
									text: row.name,
									value: row.id
								})
							})
							this.backDrawer = true;
						} else {
							uni.$u.toast('暂无可退回的节点')
						}
					}
				});
			},
			//退回确定
			submitBackForm(e) {
				if (!this.backData.destNodeId) {
					uni.$u.toast('请选择要退回的节点')
					return false;
				}
				this.$request(this.$api['workbench/back'],
					this.backData,
					res => {
						uni.$u.toast('该审批已退回到您所选择的节点')
						this.backDrawer = false;
						this.initData()
					})
			},
			//点击加签按钮弹出modal
			addSign(e) {
				this.CountersignData.procInstId = e.procInstId;
				this.showTree = true;
			},
			//前加签，后加签保存
			submitCountersignForm(e) {
				if (!this.CountersignData.userIds.length) {
					uni.$u.toast('请选择要转办的用户')
					return false;
				}
				console.log(this.CountersignData);
				this.$request(this.$api[this.signType === 1 ? 'workbench/beforeSign' :
						'workbench/afterSign'],
					this.CountersignData,
					res => {
						this.showTree = false;
						this.initData()
					})

			},
			//单选框回调
			radioChange: function(evt) {
				for (let i = 0; i < this.items.length; i++) {
					if (this.items[i].value === evt.detail.value) {
						this.currentradio = i;
						this.signType = evt.detail.value
						break;
					}
				}
			},
			//获取用户树的数据
			getTreeData() {
				this.$request(this.$api['workbench/orgUserTree'], {
					parentId: 0
				}, res => {
					this.roomTreeData = res;
					console.log(res, '=---');
				})
			},
			open() {
				// console.log('open');
			},
			close() {
				this.showTree = false
				// console.log('close');
			},
			doExpandTree(keys, expand) {
				this.$refs.DaTreeRef?.setExpandedKeys(keys, expand)

				const gek = this.$refs.DaTreeRef?.getExpandedKeys()
				console.log('当前已展开的KEY ==>', gek)
			},
			doCheckedTree(keys, checked) {
				this.$refs.DaTreeRef?.setCheckedKeys(keys, checked)

				const gek = this.$refs.DaTreeRef?.getCheckedKeys()
				console.log('当前已选中的KEY ==>', gek)
			},
			handleTreeChange1(allSelectedKeys, currentItem) {
				console.log('handleTreeChange ==>', allSelectedKeys, currentItem)
				this.delegateData.delegateUserId = allSelectedKeys.substring(4)
				this.selectedDelegateUser = currentItem.label
				// let arr = allSelectedKeys.filter(e => {
				// 	return e.indexOf('user') != -1
				// })
				// this.CountersignData.userIds = []
				// arr.forEach(e => {
				// 	this.CountersignData.userIds.push(e.substring(4))
				// })
				// console.log(this.CountersignData, 'ajdoajdo');
			},
			handleExpandChange1(expand, currentItem) {
				console.log('handleExpandChange ==>', expand, currentItem)
			},
			handleTreeChange(allSelectedKeys, currentItem) {
				console.log('handleTreeChange ==>', allSelectedKeys, currentItem)
				let arr = allSelectedKeys.filter(e => {
					return e.indexOf('user') != -1
				})
				this.CountersignData.userIds = []
				arr.forEach(e => {
					this.CountersignData.userIds.push(e.substring(4))
				})
			},
			handleExpandChange(expand, currentItem) {
				console.log('handleExpandChange ==>', expand, currentItem)
			},
			approveHistory(item) {
				let applyId = null;
				if (this.current == 0) {
					applyId = item.procInstId
				} else {
					applyId = item.id
				}
				uni.navigateTo({
					url: "./approvehistory?applyId=" + applyId
				});
			},
			rejectApprove(val) {
				this.handleDrawer = false;
				this.$refs.grid.query();
			},
			approvedProcess(val) {
				this.handleDrawer = false;
				this.$refs.grid.query();
			},
			startProcess(val) {
				this.detailDrawer = false;
				this.drawer = false;
				this.$refs.grid.query();
			},
			changeCurrent(index) {
				this.current = index
				uni.pageScrollTo({
					scrollTop: 0, //滚动到页面的目标位置
					duration: 300
				});

				this.isEmpty = false
				this.isLast = false
				this.start = 1
				this.approveData = []
				this.getTodolist()
			},
			getTodolist() {
				if (!this.isLast) {
					let params = {
						limit: 10,
						current: this.start,
						param: {
							onlyShowSpecifiedProcesses: true,
						}
					}
					uni.showLoading({
						title: '加载中'
					});
					let approveapi = this.approveApi[this.current]
					this.$request(this.$api[approveapi], params, data => {
						uni.hideLoading();
						if (data.list.length) {
							this.approveData = this.approveData.concat(data.list)
							if (data.total - params.current - params.limit > 0) {
								this.start += 1
							} else {
								this.isLast = true
							}
						} else {
							this.isEmpty = true
						}
					})

				} else {
					console.log('没数据了')
					this.isEmpty = true
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.btnstyle {
		width: auto;
		padding: 0 16rpx;
		height: 50rpx;
		float: right;
		line-height: 50rpx;
		text-align: center;
		border: 1rpx solid #f2f2f2;
		font-size: 26rpx;
		margin-right: 10rpx;
		border-radius: 10rpx;
		background-color: #11acf1;
		color: #ffffff;
	}

	.searchbox {
		display: inline-block;
		width: auto;
		height: auto;
		margin: 10rpx;
		padding: 10rpx 20rpx;
		border: 1rpx solid #f2f2f2;
	}

	.header {
		width: 100%;
		height: 300rpx;
		position: fixed;
		top: 0;
		background-image: linear-gradient(#11acf1, #ffffff);
	}

	.bodystyle {
		width: 100%;
		margin-top: 70px;
	}

	.menuStyle {
		width: 100%;
		height: 75rpx;
		line-height: 75rpx;
		text-align: center;
		padding: 0 10px;
		font-size: 30rpx;
	}

	.menuborder {
		border-bottom: 2px solid #11acf1;
	}

	.menu {
		width: 22%;
		background-color: #000000;
		margin: 10upx 1%;
	}

	.showCard {
		padding: 20upx;
		width: 94%;
		margin: 30rpx 3%;
		height: auto;
		border: 1upx solid #f2f2f2;
		box-shadow: 1px 5px 5px #f2f2f2;
		border-radius: 20rpx;
		background-color: #ffffff;
	}
	
	.showCard1 {
		padding: 20upx;
		width: 94%;
		margin: 20rpx 3%;
		height: 320rpx;
		border: 1upx solid #f2f2f2;
		box-shadow: 1px 1px 5px #f2f2f2;
	}

	.headerStyle {
		width: 100%;
		position: fixed;
		top: 0;
		height: 75rpx;
		background-color: #ffffff;
		z-index: 999;
	}
	.u-skeleton{
		height: 100vh;
	}
</style>